import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'

const service = axios.create({
  baseURL: "http://150.158.174.253:9527",
  timeout: 5000,
  withCredentials: true,
  headers: {
    Accept: "application/json"
  }
});
// 设置 get,post 默认 Content-Type
service.defaults.headers.get["Content-Type"] = "application/json";
service.defaults.headers.post["Content-Type"] ="application/x-www-form-urlencoded";

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = localStorage.getItem("token")
    }
    if (config.method === "post" || config.method === "put") {
       config.data = JSON.stringify(config.data); // post、put 提交时，将对象转换为string,
    }
    return config
  },
  error => {
    console.log("request拦截器中出错", error);
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    //console.log("响应拦截器：",response)
    const res = response.data
    switch (response.status) {
      case 200: //请求成功
        return response.data;
      case 401:
        //token失效,重新登录
         MessageBox.confirm(
           "登录失效，你可以选择继续浏览此页面或者重新登录","确认退出",{
             confirmButtonText: "重新登录",
             cancelButtonText: "取消",
             type: "warning"
           }
         ).then(() => {
           router.push("/login"); 
         });
      case 404:
        //资源不存在
        return router.push("/404")
      case 500:
        //服务器崩溃
      default:
        return Promise.reject(new Error(res.message || "Error"));
    }
  },
  error => {
    console.log("response拦截器中出错：", error);
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
)

export default service
